package com.daka.service.impl;

import com.daka.bean.CheckLogVo;
import com.daka.bean.User;
import com.daka.bean.UserVo;
import com.daka.dao.CheckLogMapper;
import com.daka.dao.UserMapper;
import com.daka.service.UserService;
import org.h2.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;

    @Autowired
    CheckLogMapper checkLogMapper;


    @Override
    public ResponseEntity insert(User user) throws ParseException {
        if (StringUtils.isNullOrEmpty(user.getNickName())) {
            throw new RuntimeException("输入昵称");
        }
        if (StringUtils.isNullOrEmpty(user.getName())) {
            throw new RuntimeException("输入打卡项目");
        }
        if (null == user.getDuration()) {
            user.setDuration(0);
        }
        LocalDateTime ldt = LocalDateTime.now();
//        Calendar calendar = Calendar.getInstance();
//        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        user.setFirstweekday(DateFormat.getDateInstance().parse(getWeekStartCorrect()));
        user.setCreatetime(Timestamp.valueOf(ldt));
        user.setYearno(2020);
        User user1 = userMapper.selectBy(user.getNickName(), user.getFirstweekday());
        if (user1 == null) {
            user.setWeekday(String.valueOf(ldt.getDayOfWeek().getValue()));
//            user.setCount(1);
            userMapper.insert(user);
        } else {
            user.setWeekday(user1.getWeekday().concat(",").concat(String.valueOf(ldt.getDayOfWeek().getValue())));
//            user.setCount(user.getWeekday().split(",").length);
            userMapper.update(user);
        }
        // 第二页传打卡记录
        checkLogMapper.log(user);

        return ResponseEntity.ok().body(user.getWeekday().length() >= 7 ? "You Got It !!!" : "打卡成功");
    }

    @Override
    public ResponseEntity findAll() throws ParseException {
        UserVo vo = new UserVo();
        Calendar calendar = Calendar.getInstance();
        List<User> list = userMapper.findAllByWeekOfYear(getWeekStartCorrect());
        //        list.forEach(i -> {
        //            i.setWeekdays(Arrays.asList(i.getWeekday().split(",")));
        //        });
        vo.setList(list);
        vo.setCount(vo.getList().size());

        return ResponseEntity.ok(vo);
    }

    @Override
    public ResponseEntity findMe(User user) {
        return null;
    }

    @Override
    public ResponseEntity findAll1() {
        UserVo vo = new UserVo();
        Calendar calendar = Calendar.getInstance();
        List<User> list = userMapper.findAllByWeekOfYear1(getWeekStartCorrect());

        list.forEach(i -> {
            i.setWeekdays(Arrays.stream(i.getWeekday().split(",")).distinct().collect(Collectors.toList()));
        });
        vo.setList(list);
        vo.setCount(vo.getList().size());

        return ResponseEntity.ok(vo);
    }

    /**
     * 每周星期天凌晨1点实行一次：
     */
    //    @Scheduled(cron = "0 0 1 ? * L")
    //    public  void clearStatus() {
    //        activityMapper.clearCount();
    //    }

    /**
     * 获取本周的第一天
     *
     * @return String
     **/
    public static String getWeekStartCorrect() {
        int num;
        Calendar calendar = Calendar.getInstance();
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        if (dayOfWeek == 1) {
            num = 0;
        } else if (dayOfWeek == 0) {
            num = -6;
        } else {
            num = 1 - dayOfWeek;
        }
        calendar.add(Calendar.DATE, num);
        Date monday = calendar.getTime();
        return new SimpleDateFormat("yyyy-MM-dd").format(monday);
    }

    @Override
    public ResponseEntity delete(User checklog) throws ParseException {
        CheckLogVo log = checkLogMapper.findOne(checklog.getId());

        Date fstday = DateFormat.getDateInstance().parse(getWeekStartCorrect());
        User user1 = userMapper.selectBy(log.getNickName(), fstday);

        Integer dow = log.getCreatetime().toLocalDateTime().getDayOfWeek().getValue();

        String newWeekDays = user1.getWeekday().replaceAll(dow.toString() + ",", "")
                .replaceAll(dow.toString() + "", "");

        user1.setWeekday(newWeekDays);
        userMapper.update(user1);
        if (newWeekDays.equals("")) {
            userMapper.delete(user1);
        }
        checkLogMapper.delete(checklog.getId());
        return ResponseEntity.ok("");
    }

    @Override
    public ResponseEntity backup() {
        userMapper.backup();
        checkLogMapper.backup();
        return ResponseEntity.ok("");
    }
}
